package com.ssyt.hiring.common.util;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;

import com.ssyt.hiring.common.Constants;

/**
 * 数据库操作工具类
 * 
 * @author Administrator
 *
 */
public class DBUtil {
	private static final Logger LOG = Logger.getLogger(Util.class);

	private DBUtil() throws IllegalAccessException {
		throw new IllegalAccessException();
	}

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection connection = null;
		try {
			Class.forName(Constants.DB_DRIVER);
			connection = DriverManager.getConnection(Constants.DB_URL,
					Constants.DB_USERNAME, Constants.DB_PASSWORD);
		} catch (ClassNotFoundException e) {
			Util.e(LOG, "数据库驱动加载失败！", e);
		} catch (SQLException e) {
			Util.e(LOG, "获取数据库连接失败！", e);

		}
		return connection;
	}

	/**
	 * 增删改操�?
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	public static int executeUpdate(String sql, Object... params) {
		int row = 0;
		Connection connection = getConnection();
		PreparedStatement preparedStatement = null;
		try {
			preparedStatement = connection.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					preparedStatement.setObject(i + 1, params[i]);
				}
			}
			row = preparedStatement.executeUpdate();
		} catch (SQLException e) {
			Util.e(LOG, "操作数据库失败，", e);
		} finally {
			DBUtil.close(preparedStatement, connection);
		}
		return row;
	}

	public static int executeUpdate(String sql, List<Object> list) {
		return executeUpdate(sql, list.toArray());
	}

	/**
	 * 关闭数据库资�?
	 */
	public static void close(PreparedStatement preparedStatement) {
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				Util.e(LOG, "preparedStatement关闭失败！", e);
			}
		}
	}

	public static void close(PreparedStatement preparedStatement,
			Connection connection) {
		close(preparedStatement);
		close(connection);
	}

	public static void close(Connection connection) {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				Util.e(LOG, "connection关闭失败！", e);
			}
		}
	}

	public static void close(ResultSet resultSet,
			PreparedStatement preparedStatement, Connection connection) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				Util.e(LOG, "resultSet关闭失败！", e);
			}
		}
		close(preparedStatement, connection);
	}

	/**
	 * 数据库事务
	 * 
	 * @param connection
	 * @param flag
	 */
	public static void setAutoCommit(Connection connection, boolean flag) {
		try {
			connection.setAutoCommit(flag);
		} catch (Exception e) {
			Util.e(LOG, "数据库事物异常！", e);
		}
	}

	/**
	 * 查询，返回对象集
	 * 
	 * @param clazz
	 * @param sql
	 * @param params
	 * @return
	 */
	public static <T> List<T> executeQuery(Class<T> clazz, String sql,
			Object... params) {
		return executeQuery(clazz, sql, Arrays.asList(params));
	}

	public static <T> List<T> executeQuery(Class<T> clazz, String sql,
			List<Object> paramList) {
		Validate.notNull(clazz, "参数clazz不能为空" + clazz);
		Validate.notBlank(sql, "参数sql不能为空" + sql);

		List<T> resultList = new ArrayList<T>();
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			connection = DBUtil.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			setParameter(paramList, preparedStatement);
			resultSet = preparedStatement.executeQuery();
			// 读取查询结果集的底层结构
			ResultSetMetaData metaDate = resultSet.getMetaData();
			// 得到查询了多少列信息
			int columns = metaDate.getColumnCount();
			// 反射得到所有私有属性
			Field[] declaredFields = clazz.getDeclaredFields();
			// 循环每条结果，并把结果封装成具体的实体对象，最后放到返回集合中
			while (resultSet.next()) {
				// 利用反射实例化clazz对象
				T obj = clazz.newInstance();
				// 对每列循环，把对应的值赋对obj的相应属性
				for (int i = 1; i <= columns; i++) {
					// 获取查询字段别名
					String columnLabel = metaDate.getColumnLabel(i);
					// 遍历属性数组
					for (Field field : declaredFields) {
						// 设置允许操作私有属性
						field.setAccessible(true);
						// 获取当前属性的类型
						Class<?> fieldClass = field.getType();
						// 获取当前属性的名字
						String fieldName = field.getName();
						// 某个属性有大写，表示需要属性名与数据库列名对应
						if (isContainsAlphaUpper(fieldName)) {
							String columnName = toColumnName(fieldName);
							if (columnLabel.equals(columnName)) {
								setFieldValue(resultSet, obj, columnLabel,
										field, fieldClass);
							}
						} else {
							if (columnLabel.equals(fieldName)) {
								setFieldValue(resultSet, obj, columnLabel,
										field, fieldClass);
							}
						}
					}
				}
				resultList.add(obj);
			}
			return resultList;
		} catch (Exception e) {
			Util.e(LOG, "数据查询失败", e);
		} finally {
			DBUtil.close(resultSet, preparedStatement, connection);
		}
		return resultList;
	}

	/**
	 * 判断字符串里是否有大写字母
	 * 
	 * @param fieldName
	 * @return
	 */
	private static boolean isContainsAlphaUpper(String fieldName) {
		Validate.notBlank(fieldName, "参数fieldName不能为空" + fieldName);
		for (int i = 0; i < fieldName.length(); i++) {
			if (CharUtils.isAsciiAlphaUpper(fieldName.charAt(i))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Java属性 -> 数据库字段名：helloWorld -> hello_world
	 * 
	 * @param fieldName
	 * @return
	 */
	private static String toColumnName(String fieldName) {
		if (fieldName == null) {
			return "";
		}

		char[] chars = fieldName.toCharArray();
		StringBuilder sb = new StringBuilder();
		for (char c : chars) {
			if (CharUtils.isAsciiAlphaUpper(c)) {
				sb.append("_" + (char) (c + 32));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * prepareStatement参数设置
	 * 
	 * @param paramList
	 * @param preparedStatement
	 * @throws SQLException
	 */
	private static void setParameter(List<Object> paramList,
			PreparedStatement preparedStatement) throws SQLException {
		if (!paramList.isEmpty()) {
			for (int i = 0; i < paramList.size(); i++) {
				preparedStatement.setObject(i + 1, paramList.get(i));
			}
		}
	}

	/**
	 * 利用反射实现JavaBean的自动赋�?
	 * 
	 * @param resultSet
	 * @param obj
	 * @param columnName
	 * @param field
	 * @param fieldClass
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */

	private static <T> void setFieldValue(ResultSet resultSet, T obj,
			String columnName, Field field, Class<?> fieldClass)
			throws IllegalAccessException, SQLException {
		// FIXME
		if (fieldClass.equals(int.class) || fieldClass.equals(Integer.class)) {
			field.set(obj, resultSet.getInt(columnName));
		} else if (fieldClass.equals(long.class)
				|| fieldClass.equals(Long.class)) {
			field.set(obj, resultSet.getLong(columnName));
		} else if (fieldClass.equals(String.class)) {
			field.set(obj, resultSet.getString(columnName));
		} else if (fieldClass.equals(BigDecimal.class)) {
			field.set(obj, resultSet.getBigDecimal(columnName));
		} else if (fieldClass.equals(Date.class)) {
			field.set(obj, resultSet.getTimestamp(columnName));
		}
	}

	/**
	 * 查询：返回单�?对象
	 * 
	 * @param clazz
	 * @param sql
	 * @param paramList
	 * @return
	 */
	public static <T> T getUniqueResult(Class<T> clazz, String sql,
			List<Object> paramList) {
		List<T> list = executeQuery(clazz, sql, paramList);
		if (list.isEmpty()) {
			return null;
		} else {
			return list.get(0);
		}
	}

	/**
	 * 查询：返回单�?对象
	 * 
	 * @param clazz
	 * @param sql
	 * @param paramList
	 * @return
	 */
	public static <T> T getUniqueResult(Class<T> clazz, String sql,
			Object... params) {
		return getUniqueResult(clazz, sql, Arrays.asList(params));
	}

	/**
	 * 查询总记录数
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	public static int getAllRecords(String sql, Object... params) {
		return getAllRecords(sql, Arrays.asList(params));
	}

	public static int getAllRecords(String sql, List<Object> paramList) {
		int count = 0;
		Connection connection = getConnection();
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			preparedStatement = connection.prepareStatement(sql);
			setParameter(paramList, preparedStatement);
			resultSet = preparedStatement.executeQuery();
			resultSet.next();
			count = resultSet.getInt("COUNT(*)");
		} catch (SQLException e) {
			Util.e(LOG, "操作数据库失败，", e);
		} finally {
			DBUtil.close(resultSet, preparedStatement, connection);
		}
		return count;
	}
}
